package com.buaa.xxx0321;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {

    private SeekBar sb;
    private MusicService.MyBinder myBinder;
    private Handler handler;
    private boolean isRun = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sb = (SeekBar) findViewById(R.id.sb);
        final Intent intent = new Intent("myMusic");
        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myBinder = (MusicService.MyBinder)service;
                Thread t = new Thread() {
                    @Override
                    public void run() {
                        int pro = 0;
                        while (pro < 800 && isRun) {
                            try {
                                Thread.sleep(30);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            pro = myBinder.getProgress();
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putInt("pro",pro);
                            msg.setData(bundle);
                            handler.sendMessage(msg);
                        }
                    }
                };
                t.start();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        },BIND_AUTO_CREATE);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                sb.setProgress(msg.getData().getInt("pro"));
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRun = false;
    }

    public void play(View view) {
        Intent intent = new Intent("myMusic");
        intent.putExtra("action",1);
        startService(intent);
    }

    public void pause(View view) {
        Intent intent = new Intent("myMusic");
        intent.putExtra("action",2);
        startService(intent);
    }

    public void resume(View view) {
        Intent intent = new Intent("myMusic");
        intent.putExtra("action",3);
        startService(intent);
    }
}
